import 'package:flutter/material.dart';
import 'package:upgrader/upgrader.dart';

class MyUpgrader extends Upgrader {
  MyUpgrader(
      {super.debugLogging,
      super.client,
      super.clientHeaders,
      super.storeController});
  @override
  bool isUpdateAvailable() {
    final storeVersion = currentAppStoreVersion;
    final installedVersion = currentInstalledVersion;
    print('storeVersion=$storeVersion');
    print('installedVersion=$installedVersion');
    return false;
    return compareVersions(storeVersion, installedVersion) > 0;
    return super.isUpdateAvailable();
  }

  // 比较版本号的实用函数
  /// 比较两个版本号
  /// 返回:
  ///   -1: version1 < version2
  ///    0: version1 == version2
  ///    1: version1 > version2
  int compareVersions(String? version1, String? version2) {
    final v1Parts =
        version1?.split('.').map((e) => int.tryParse(e) ?? 0).toList();
    final v2Parts =
        version2?.split('.').map((e) => int.tryParse(e) ?? 0).toList();

    final maxLength = (v1Parts?.length ?? 0) > (v2Parts?.length ?? 0)
        ? (v1Parts?.length ?? 0)
        : (v2Parts?.length ?? 0);

    for (int i = 0; i < maxLength; i++) {
      final v1 = (v1Parts != null && i < v1Parts.length) ? v1Parts[i] : 0;
      final v2 = (v2Parts != null && i < v2Parts.length) ? v2Parts[i] : 0;

      if (v1 > v2) return 1;
      if (v1 < v2) return -1;
    }

    return 0;
  }
}

class MyUpgradeAlert extends UpgradeAlert {
  MyUpgradeAlert({super.key, super.upgrader, super.child});

  /// Override the [createState] method to provide a custom class
  /// with overridden methods.
  @override
  UpgradeAlertState createState() => MyUpgradeAlertState();
}

class MyUpgradeAlertState extends UpgradeAlertState {
  @override
  void showTheDialog({
    Key? key,
    required BuildContext context,
    required String? title,
    required String message,
    required String? releaseNotes,
    required bool barrierDismissible,
    required UpgraderMessages messages,
  }) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            key: key,
            title: const Text('有新版本，请更新'),
            content: const SingleChildScrollView(
              child: ListBody(
                children: <Widget>[
                  Text('有新版本，请更新'),
                ],
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text('稍后'),
                onPressed: () {
                  onUserIgnored(context, true);
                },
              ),
              TextButton(
                child: const Text('更新'),
                onPressed: () {
                  onUserUpdated(context, !widget.upgrader.blocked());
                },
              ),
            ],
          );
        });
  }
}
